<template>
  <div class="feedback-container">
    <el-card class="feedback-card">
      <template #header>
        <div class="card-header">
          <h2>用户反馈管理</h2>
          <div class="header-actions">
            <el-button type="primary" @click="refreshList">刷新</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" class="search-form">
        <el-form-item label="反馈类型">
          <el-select
            v-model="queryParams.feedbackType"
            placeholder="全部"
            clearable
            class="status-select"
          >
            <el-option label="功能建议" value="功能建议" class="status-option" />
            <el-option label="界面问题" value="界面问题" class="status-option" />
            <el-option label="操作体验" value="操作体验" class="status-option" />
            <el-option label="其他" value="其他" class="status-option" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select
            v-model="queryParams.status"
            placeholder="全部"
            clearable
            class="status-select"
          >
            <el-option label="待处理" value="待处理" class="status-option" />
            <el-option label="已确认" value="已确认" class="status-option" />
            <el-option label="处理中" value="处理中" class="status-option" />
            <el-option label="已完成" value="已完成" class="status-option" />
            <el-option label="已拒绝" value="已拒绝" class="status-option" />
          </el-select>
        </el-form-item>
        <el-form-item label="关键词">
          <el-input v-model="queryParams.keyword" placeholder="内容关键词" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">搜索</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="feedbackList"
        border
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="用户" width="100" />
        <el-table-column prop="feedbackType" label="反馈类型" width="100" />
        <el-table-column prop="content" label="反馈内容" show-overflow-tooltip />
        <el-table-column prop="contact" label="联系方式" width="150" show-overflow-tooltip />
        <el-table-column prop="deviceInfo" label="设备信息" width="150" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ new Date(scope.row.createdAt).toLocaleDateString() }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button link type="primary" @click="handleDetail(scope.row)">详情</el-button>
            <el-button link type="primary" @click="handleUpdate(scope.row)">更新状态</el-button>
            <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.current"
          v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 反馈详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="反馈详情"
      width="500px"
      destroy-on-close
      append-to-body
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="ID">{{ currentFeedback.id }}</el-descriptions-item>
        <el-descriptions-item label="用户">{{ currentFeedback.username }}</el-descriptions-item>
        <el-descriptions-item label="反馈类型">{{
          currentFeedback.feedbackType
        }}</el-descriptions-item>
        <el-descriptions-item label="反馈内容">{{ currentFeedback.content }}</el-descriptions-item>
        <el-descriptions-item label="联系方式">{{ currentFeedback.contact }}</el-descriptions-item>
        <el-descriptions-item label="设备信息">{{
          currentFeedback.deviceInfo
        }}</el-descriptions-item>
        <el-descriptions-item label="状态">{{ currentFeedback.status }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{
          currentFeedback.createdAt ? new Date(currentFeedback.createdAt).toLocaleDateString() : ''
        }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{
          currentFeedback.updatedAt ? new Date(currentFeedback.updatedAt).toLocaleDateString() : ''
        }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog
      v-model="updateVisible"
      title="更新反馈状态"
      width="400px"
      destroy-on-close
      append-to-body
    >
      <el-form :model="updateForm" label-width="80px">
        <el-form-item label="状态">
          <el-select v-model="updateForm.status" placeholder="请选择状态">
            <el-option label="待处理" value="待处理" />
            <el-option label="已确认" value="已确认" />
            <el-option label="处理中" value="处理中" />
            <el-option label="已完成" value="已完成" />
            <el-option label="已拒绝" value="已拒绝" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="updateVisible = false">取消</el-button>
        <el-button type="primary" @click="submitStatusUpdate">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getAllFeedbackList,
  updateFeedback,
  deleteFeedback,
  getFeedbackDetail,
  type FeedbackType,
  type FeedbackQuery,
  type ApiResponse,
  type PageResult,
} from '@/api/feedback'

// 查询参数
const queryParams = reactive<FeedbackQuery>({
  current: 1,
  pageSize: 10,
})

// 列表数据
const loading = ref(false)
const total = ref(0)
const feedbackList = ref<FeedbackType[]>([])
const selectedRows = ref<FeedbackType[]>([])

// 详情对话框
const detailVisible = ref(false)
const currentFeedback = ref<FeedbackType>({
  feedbackType: '',
  content: '',
})

// 状态更新对话框
const updateVisible = ref(false)
const updateForm = reactive({
  id: 0,
  status: '',
})

// 获取反馈列表
const getList = async () => {
  loading.value = true
  try {
    const response = (await getAllFeedbackList(queryParams)) as unknown as ApiResponse<
      PageResult<FeedbackType>
    >

    if (response.code === 200 && response.data) {
      feedbackList.value = response.data.records
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取反馈列表失败')
    }
  } catch (error) {
    console.error('获取反馈列表出错:', error)
    ElMessage.error('获取反馈列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleQuery = () => {
  queryParams.current = 1
  getList()
}

// 重置搜索
const resetQuery = () => {
  queryParams.current = 1
  queryParams.keyword = undefined
  queryParams.status = undefined
  queryParams.feedbackType = undefined
  getList()
}

// 刷新列表
const refreshList = () => {
  getList()
}

// 处理多选
const handleSelectionChange = (selection: FeedbackType[]) => {
  selectedRows.value = selection
}

// 改变页码
const handleCurrentChange = (page: number) => {
  queryParams.current = page
  getList()
}

// 改变每页数量
const handleSizeChange = (size: number) => {
  queryParams.pageSize = size
  queryParams.current = 1
  getList()
}

// 查看详情
const handleDetail = async (row: FeedbackType) => {
  try {
    const response = (await getFeedbackDetail(
      row.id as number,
    )) as unknown as ApiResponse<FeedbackType>

    if (response.code === 200 && response.data) {
      currentFeedback.value = response.data
      detailVisible.value = true
    } else {
      ElMessage.error(response.message || '获取反馈详情失败')
    }
  } catch (error) {
    console.error('获取反馈详情出错:', error)
    ElMessage.error('获取反馈详情失败')
  }
}

// 打开更新状态对话框
const handleUpdate = (row: FeedbackType) => {
  updateForm.id = row.id as number
  updateForm.status = row.status || '待处理'
  updateVisible.value = true
}

// 提交状态更新
const submitStatusUpdate = async () => {
  try {
    const response = (await updateFeedback({
      id: updateForm.id,
      status: updateForm.status,
    })) as unknown as ApiResponse<boolean>

    if (response.code === 200 && response.data) {
      ElMessage.success('更新反馈状态成功')
      updateVisible.value = false
      getList()
    } else {
      ElMessage.error(response.message || '更新反馈状态失败')
    }
  } catch (error) {
    console.error('更新反馈状态出错:', error)
    ElMessage.error('更新反馈状态失败')
  }
}

// 删除反馈
const handleDelete = (row: FeedbackType) => {
  ElMessageBox.confirm('是否确认删除该反馈?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const response = (await deleteFeedback(row.id as number)) as unknown as ApiResponse<boolean>

        if (response.code === 200 && response.data) {
          ElMessage.success('删除成功')
          getList()
        } else {
          ElMessage.error(response.message || '删除失败')
        }
      } catch (error) {
        console.error('删除反馈出错:', error)
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {})
}

// 获取状态对应的标签类型
const getStatusType = (status: string) => {
  const statusMap: Record<string, string> = {
    待处理: '',
    已确认: 'info',
    处理中: 'warning',
    已完成: 'success',
    已拒绝: 'danger',
  }
  return statusMap[status] || ''
}

// 页面加载时获取列表
onMounted(() => {
  getList()
})
</script>

<style scoped>
.feedback-container {
  padding: 20px;
}

.feedback-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 添加下拉框样式修复 */
.status-select {
  width: 150px;
}
.status-select :deep(.el-input__inner) {
  text-align: left;
}
.status-option {
  font-size: 14px;
  padding: 8px 12px;
}
</style>
